package com.youlu.campus.starter.trace.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.youlu.campus.starter.trace.thread.LogTraceThreadPoolExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 异步线程池 处理
 */
public class LogTraceAsyncConfig implements AsyncConfigurer {

    // 获取CPU核心数
    private static int cpuCores = Runtime.getRuntime().availableProcessors();
    // 计算核心线程数： IO密集型任务  经过测试，CPU核心数 x 4 服务器CPU最高使用率是 50%左右 考虑一个服务器部署多个服务 最高使用百分之50 可接收
    private static int corePoolSize = cpuCores * 3;
    // 计算最大线程数：核心线程数的 6 倍，用于应对突发流量
    private static int maximumPoolSize = corePoolSize * 6;
    // 空闲线程存活时间：30秒
    private static long keepAliveTime = 30L;
    // 使用有界队列，容量1000 最大任务数量
    private static BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);
    // 使用 CallerRunsPolicy 拒绝策略
    private static RejectedExecutionHandler rejectedHandler = new ThreadPoolExecutor.CallerRunsPolicy();

    public Executor getAsyncExecutor() {
        return new LogTraceThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                new ThreadFactoryBuilder().setNameFormat("sendmsg-pool-%d").build(),
                rejectedHandler);
    }
}